<?php
define("IN_SYS", true);

function template($view) {
    if (!file_exists($view)) {
        
    }
    $file_path = _createFile($view);
    return $file_path;
}

// 生成文件
function _createFile($view,$compile_dir = null) {
    $save_dir = _getSaveDir($view,$compile_dir);
    if(!file_exists($save_dir)){
        mkdir($save_dir, 0777,TRUE);
    }
    $file_path = _getRealTplFile($view);
    $compile_file = $save_dir.basename($file_path);
    if(!file_exists($compile_file) || (file_exists($compile_file) && filemtime($file_path) > filemtime($compile_file))){
        _compile($file_path,$compile_file);
    }
    return $compile_file;
}

// 获取文件保存路径
function _getSaveDir($tpl_file, $compile_dir=NULL){
    $tpl_file = _cleanTplPath($tpl_file);
    $file_dir = dirname($tpl_file);
    if(!isset($compile_dir)){
        $compile_dir = __COMPILE_DIR__;
    }
    $save_dir = $compile_dir.$file_dir.'/';
    return $save_dir;
}

/*
 * 编辑文件
 */
function _compile($src_file,$desc_file){
    $content = file_get_contents($src_file);
    $content = parse($content);
    file_put_contents($desc_file, $content);
}

/**
 * 解析文件
 * @param string $tpl_file  文件路径
 * @return mixed
 */
function parse($template, $add_header=true)
{
    if ($add_header)
    {
        $template = "<?php defined('IN_SYS') OR exit('Access Denied'); ?>\r\n".$template;
    }
    $template = preg_replace("~([\n\r\t]*)\<\!\-\-\s*\{(.+?)\}\s*\-\-\>([\n\r\t]*)~is", "\\1{\\2}\\3", $template);
    $template = preg_replace("~([\n\r\t]*)\{include\s+(.+?)\}([\n\r\t]*)~is", "\\1<?php include template(\\2); ?>\\3", $template);
    $template = preg_replace("~\{CONSTANT\[['\"]?([a-zA-Z0-9_]+)['\"]?\]\}~is", "<?php if(defined('\\1')){echo \\1;}?>", $template);
    $template = preg_replace('~\{(([ \(\)\[\]\'\"\$\w_\.]+)([ ]*[\+\-\*%\/][ ]*([ \(\)\[\]\'\"\$\w_\.]+))+)\}~is', "<?php echo \\1;?>", $template);// 四则运算
    $template = preg_replace("~\{(\\\$[a-zA-Z0-9_\[\]\-\>'\"\$\x7f-\xff]+)\}~is", "<?php if(isset(\\1)){echo \\1;}?>", $template);
    $template = preg_replace("~\{([a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+(::[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+))\}~is", "<?php echo \\1;?>", $template);// static
    $template = preg_replace("~\{(\\\$[a-zA-Z0-9_\[\]\-\>'\"\.\$\x7f-\xff]+)\s*\|\s*default:\s*([^\{\}]*)\}~is", "<?php if(isset(\\1)){echo \\1;}else{echo \\2;}?>", $template);
    $template = preg_replace("~\{([@&\\\$a-zA-Z0-9_:]+)\((.*?)\)\}~is", "<?php echo @\\1(\\2);?>", $template);// 函数
    $template = preg_replace_callback("~([\n\r\t]*)\{elseif\s+(.+?)\}([\n\r\t]*)~is", function($matches){
        return _stripvtags("<?php } elseif({$matches[2]}) { ?>",'');
    }, $template);
    $template = preg_replace("~([\n\r\t]*)\{else\}([\n\r\t]*)~is", "<?php } else { ?>", $template);

    for($i = 0; $i <= 8; $i++)
    {
        $template = preg_replace_callback("~([\n\r\t]*)\{loop\s+(\S+)\s+(\S+)\}([\n\r\t]*)(.+?)([\n\r\t]*)\{\/loop\}([\n\r\t]*)~is", function($matches){
            return _stripvtags("{$matches[1]}<?php if(isset({$matches[2]}) && is_array({$matches[2]})){ foreach({$matches[2]} as {$matches[3]}){ ?>{$matches[4]}", "{$matches[5]}{$matches[6]}<?php }}?>{$matches[7]}");
        }, $template);

        $template = preg_replace_callback("~([\n\r\t]*)\{for\s+(.+?);\s*(.+?);\s*(.+?)\}([\n\r\t]*)(.+?)([\n\r\t]*)\{\/for\}([\n\r\t]*)~is", function($matches){
            return _stripvtags("{$matches[1]}<?php for({$matches[2]}; {$matches[3]}; {$matches[4]}){ ?>{$matches[5]}", "{$matches[6]}{$matches[7]}<?php }?>{$matches[8]}");
        }, $template);

        $template = preg_replace_callback("~([\n\r\t]*)\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}([\n\r\t]*)(.+?)([\n\r\t]*)\{\/loop\}([\n\r\t]*)~is", function($matches){
            return _stripvtags("{$matches[1]}<?php if(isset({$matches[2]}) && is_array({$matches[2]})){ foreach({$matches[2]} as {$matches[3]} => {$matches[4]}){ ?>{$matches[5]}", "{$matches[6]}{$matches[7]}<?php }}?>{$matches[8]}");
        }
            , $template);

        $template = preg_replace_callback("~([\n\r\t]*)\{if\s+(.+?)\}([\n\r\t]*?)(.+?)([\n\r\t]*)\{\/if\}([\n\r\t]*)~is", function($matches){
            return _stripvtags("{$matches[1]}<?php if({$matches[2]}) { ?>{$matches[3]}", "{$matches[4]}{$matches[5]}<?php } ?>{$matches[6]}");
        }, $template);
    }
    return $template;
}

/**
 * 取得模板绝对路径
 */
function _getRealTplFile($tpl_file)
{
    $tpl_file = _cleanTplPath($tpl_file);
    return _cleanMultiSlash(__ROOT__.__TEMPLATE_DIR__.'/'.$tpl_file);
}

/**
 * 清理模板路径
 * @param string $tpl_file  模板路径
 * @return mixed
 */
function _cleanTplPath($tpl_file)
{
    $tpl_file = str_replace('../', '/', $tpl_file);
    $tpl_file = str_replace('./', '', $tpl_file);
    $tpl_file = str_replace(__ROOT__, '/', $tpl_file);
    $tpl_file = preg_replace('~^\/'.__TEMPLATE_DIR__.'\/(.*)~is', '\\1', $tpl_file);
    return _cleanMultiSlash($tpl_file);
}

/**
 * 清理掉多余的/
 * @param string $path
 * @return mixed
 */
function _cleanMultiSlash($path)
{
    return preg_replace('~\/{2,}~is', '/', $path);
}

/**
 * 过滤转义字符
 * @param string $expr	前段
 * @param string $statement 后段
 * @return string
 */
function _stripvtags($expr, $statement)
{
    $expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
    $statement = str_replace("\\\"", "\"", $statement);
    return $expr.$statement;
}
